<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      ref="queryFormRef"
      :inline="true"
      :model="queryParams"
      class="-mb-15px"
      label-width="68px"
    >
      <el-form-item label="客户名称" prop="name">
        <el-input
          v-model="queryParams.name"
          class="!w-240px"
          clearable
          placeholder="请输入客户名称"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系人" prop="contactPerson">
        <el-input
          v-model="queryParams.contactPerson"
          class="!w-240px"
          clearable
          placeholder="请输入联系人"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
          end-placeholder="结束日期"
          start-placeholder="开始日期"
          type="daterange"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon class="mr-5px" icon="ep:search" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon class="mr-5px" icon="ep:refresh" />
          重置
        </el-button>
        <el-button
          v-hasPermi="['dk:customer:create']"
          plain
          type="primary"
          @click="openForm('create')"
        >
          <Icon class="mr-5px" icon="ep:plus" />
          新增
        </el-button>
        <el-button
          v-hasPermi="['dk:customer:export']"
          :loading="exportLoading"
          plain
          type="success"
          @click="handleExport"
        >
          <Icon class="mr-5px" icon="ep:download" />
          导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      v-loading="loading"
      :data="list"
      :show-overflow-tooltip="true"
      :stripe="true"
      @row-click="handleRowClick"
    >
      <el-table-column align="center" label="序号" type="index" width="60" />
      <el-table-column align="center" label="客户名称" prop="name" />
      <!--      <el-table-column align="center" label="单位性质" prop="companyType">-->
      <!--        <template #default="scope">-->
      <!--          <dict-tag :type="DICT_TYPE.UNIT_NATURE" :value="scope.row.companyType" />-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column align="center" label="联系人" prop="contactPerson" />
      <el-table-column align="center" label="联系电话" prop="contactPhone" />
      <el-table-column align="center" label="区域" prop="province" />
      <el-table-column
        :formatter="dateFormatter"
        align="center"
        label="创建时间"
        prop="createTime"
        width="180px"
      />
      <el-table-column align="center" label="操作" min-width="180px">
        <template #default="scope">
          <el-button
            v-hasPermi="['dk:customer:update']"
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
          >
            编辑
          </el-button>
          <el-button
            v-hasPermi="['dk:customer:delete']"
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
          >
            删除
          </el-button>
          <el-button
            v-hasPermi="['dk:customer:addproject']"
            link
            type="success"
            @click="handleCreateProject(scope.row)"
          >
            新增项目
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      v-model:limit="queryParams.pageSize"
      v-model:page="queryParams.pageNo"
      :total="total"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <CustomerForm ref="formRef" @success="getList" />

  <!-- 添加项目表单组件 -->
  <ProjectForm ref="projectFormRef" />
</template>

<script lang="ts" setup>
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { CustomerApi, CustomerVO } from '@/api/dk/customer'
import CustomerForm from './CustomerForm.vue'
import { useCustomerStore } from '@/store/modules/customer/customer'
import ProjectForm from '@/views/project/list/ProjectForm.vue'
import { useRoute } from 'vue-router'

const route = useRoute()
/** 客户 列表 */
defineOptions({ name: 'Customer' })
/** 项目表单引用 */
const projectFormRef = ref()
const isMy = ref(false)

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<CustomerVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  name: undefined,
  contactPerson: undefined,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

const customerStore = useCustomerStore()

const emit = defineEmits(['select'])

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    customerStore.loadAreaData() // 预加载地区数据
    console.log('isMy', isMy.value)
    if (isMy.value) {
      // 同时发起两个请求
      const [data] = await Promise.all([CustomerApi.getMyCustomerPage(queryParams)])
      list.value = data.list
      total.value = data.total
    } else {
      // 同时发起两个请求
      const [data] = await Promise.all([CustomerApi.getCustomerPage(queryParams)])
      list.value = data.list
      total.value = data.total
    }
  } finally {
    loading.value = false

  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await CustomerApi.deleteCustomer(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await CustomerApi.exportCustomer(queryParams)
    download.excel(data, '客户.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 修改表格行点击事件 */
const handleRowClick = (row: CustomerVO) => {
  emit('select', {
    name: row.name,
    contactPerson: row.contactPerson,
    contactPhone: row.contactPhone,
    address: row.address // 确保传递地址信息
  })
}

/** 处理新增项目 */
const handleCreateProject = (row: CustomerVO) => {
  // 打开项目表单并传递客户信息
  projectFormRef.value?.open('create', undefined, {
    companyName: row.name,
    contactPerson: row.contactPerson,
    contactPhone: row.contactPhone,
    receivingUnit: row.name,
    receivingAddress: row.address
  })
}

/** 初始化 **/
onMounted(() => {
  var fullPath = route.fullPath
  console.log('fullPath:', fullPath)
  if (fullPath === '/dk/mycustomer') {
    isMy.value = true
  }else {
    isMy.value = false
  }
  getList()
})
</script>
